package cn.kgc.springboot.redis;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DigestUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 课工场
 * @date 2023/11/15
 * @description
 */
public class RedisCache implements Cache {

    //  缓存的命名空间名称
    private  String id;


    public  RedisCache (String id){
        System.out.println("id = " + id);
        this.id = id;
    }


    @Override
    public String getId() {

        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {

//        System.out.println("==========缓存数据到Redis=============");
//        System.out.println("key = " + key + ", value = " + value);

        RedisTemplate redisTemplate = redisTemplate();

        redisTemplate.opsForHash().put(id,DigestUtils.sha1DigestAsHex(key.toString()),value);
    }

    @Override
    public Object getObject(Object key) {

//        System.out.println("=========从Redis中获取缓存数据=============");
//        System.out.println("key = " + key);
        RedisTemplate redisTemplate = redisTemplate();
        Object o = redisTemplate.opsForHash().get(id, DigestUtils.sha1DigestAsHex(key.toString()));
        return o ;
    }

    @Override
    public Object removeObject(Object key) {
//        System.out.println("---------removeObject---------");
        return null;
    }

    @Override
    public void clear() {
//        System.out.println("---------clear()---------");
        //  清空缓存
        RedisTemplate redisTemplate = redisTemplate();
        redisTemplate.delete(id);
    }

    @Override
    public int getSize() {

        RedisTemplate redisTemplate = redisTemplate();
        return redisTemplate.opsForHash().size(id).intValue();
    }


    //  获取redisTemplate对象的方法
    public  RedisTemplate  redisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        // 设置redis 中key的序列化方案 是string
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //设置hash 中key的序列化方案 是string
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        return redisTemplate;
    }
}
